// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
    this.getTokens()
  },
  globalData: {
    userInfo: null,
    baseURL: 'https://toutiao.itheima.net/v1_0',
    Authorization: '',
    tokens: {}
  },
  getTokens(jump = false) {
    wx.getStorage({
      key: 'tokens',
      success: (res) => {
        console.log(res);
        this.globalData.tokens = res.data
        if (jump) {
          this.globalData.Authorization = 'Bearer ' + res.data.token
        } else {
        wx.request({
          url: this.globalData.baseURL + '/authorizations',
          method: 'PUT',
          header: {
            Authorization: 'Bearer ' + this.globalData.tokens.refresh_token
          },
          success: ({data: {data}})=>{
            if (data !== undefined) {
              console.log('Get NewToken Okay', data);
              this.globalData.tokens.token = data.token
              this.globalData.Authorization = 'Bearer ' + data.token
            } else {
              this.globalData.tokens = {}
              this.globalData.Authorization = ''
              wx.removeStorage({
                key: 'tokens',
              })
            }
          },
          fail: ()=> {
            this.globalData.tokens = {}
            wx.removeStorage({
              key: 'tokens',
            })
          }
        })
      }
      },
      fail: () => {
        this.globalData.tokens = {}
      }
    })
  }
})
